#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from schema import *
import urlparse, logging

class LinkAdder(webapp.RequestHandler):
  def post(self):

    # Create an absolute URL
    fetch_key = self.request.get("fetch_key")
    fetch = Fetch.get(db.Key(fetch_key))
    url = self.request.get("url")
    canonical_url = urlparse.urljoin(fetch.document.url, url)
    logging.debug("Canonical URL is %s." % canonical_url)

    # Ensure that there is a document for the URL
    key_name = key_name_from_url(canonical_url)
    target = Document.get_by_key_name(key_name)
    if target is None:
      logging.debug("This taget has not been seen before.")
      try:
        target = Document(key_name=key_name, url=canonical_url)
      except db.BadValueError:
        logging.error("%s is a bad URL." % canonical_url)
      else:
        target.put()

    # Add this link to the link graph
    logging.debug("The target is %s" % str(target.key()))
    computationid = long(self.request.get("computationid"))
    logging.debug("This is on behalf of computation %i." % computationid)
    node = LinkGraphNode(
      computationid=computationid,
      docid=fetch.docid,
      links=db.Blob(checksum_from_key_name(key_name))
    )
    node.put()
    logging.debug("I added a link to the graph.")


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
    ('/add-link', LinkAdder),
  ]))

if __name__ == '__main__':
  main()
